//
//  LivingfunctionView.m
//  LiveStar
//
//  Created by 漪珊 on 2016/12/20.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "LivingfunctionView.h"
#import "LSAudienceListTableView.h"
#import "LSMsgModel.h"
@interface LivingfunctionView()<UITableViewDelegate,UITableViewDataSource>
{
    
    UITextField *_msgInputFeild;
    int _memberCount;
    NSArray *_presentArr;
    LSAudienceListTableView *_audienceTableView;
}
@end
@implementation LivingfunctionView

- (void)awakeFromNib {
    [super awakeFromNib];
    _is_Msg = NO;
    self.presentAniView.alpha = 0;
    _presentArr = @[@"animation_1",@"animation_2",@"animation_3",@"animation_4",@"animation_5",@"animation_6",];
    _memberCount = 1;
    self.onlineNum.text = @"";
    kImageViewRadius(self.sendUserIocn, self.sendUserIocn.width/2);
    kImageViewRadius(self.StarPhoto, self.StarPhoto.height/2);
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameDidChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
    if ([KString([[LSUserInfoManager sharedManager] currentUserInfo].u_type) isEqualToString:@"100"]) {
        self.focusBtn.hidden = YES;
    } else {
        self.focusBtn.hidden = NO;
    }
    self.enterAnimationView.alpha = 0.0;
    kViewRadius(self.presentAniView, self.presentAniView.height/2.0f);
    self.presentAniView.hidden = NO;
}

- (void)EnterRoomAnimationWithUsername:(NSString *)userName Level:(NSString *)level {
    self.enterTitle.text = [NSString stringWithFormat:@"%@ : 进入直播间",userName];
    switch ([level intValue]) {
        case 3:
            self.enterBackImg.image = kSET_IMAGE(@"enterAnimation_3");
            break;
        case 4:
            self.enterBackImg.image = kSET_IMAGE(@"enterAnimation_4");
            break;
        case 5:
            self.enterBackImg.image = kSET_IMAGE(@"enterAnimation_5");
            break;
            
        default:
            break;
    }
    
    [UIView animateWithDuration:2.0 delay:0.0 options:UIViewAnimationOptionTransitionFlipFromLeft animations:^{
        self.enterAnimationView.alpha = 1.0;
    }completion:^(BOOL finished) {
        [UIView animateWithDuration:0.3 animations:^{
            self.enterAnimationView.alpha = 0;
        }];
    }];
}
- (void)initAudienceList {
    _audienceTableView = [[LSAudienceListTableView alloc] initWithFrame:CGRectMake(self.starInfoView.right,self.starInfoView.y, self.width - self.starInfoView.width- 50, self.starInfoView.height) style:UITableViewStyleGrouped liveInfo:nil];
    _audienceTableView.transform = CGAffineTransformMakeRotation(- M_PI/2);
    _audienceTableView.audienceListDelegate = self;
    
    [self addSubview:_audienceTableView];
}


- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)setMsgHandler:(AVIMMsgHandler *)msgHandler {
    _msgHandler = msgHandler;
    _msgHandler.roomIMListener = self;
}

#pragma mark - AVIMMsgListener

-(void)onRecvGroupSender:(IMUserAble *)info textMsg:(NSString *)msgText{
    
    switch (info.cmdType) {
        case AVIMCMD_Custom_Text: {
            LSMsgModel *msgModel = [[LSMsgModel alloc] init];
            msgModel.userName = [info imUserName];
            msgModel.userMsg  =  msgText;
            
            msgModel.userHeadImageUrl = info.imUserIconUrl;
            msgModel.userLevel = KString(info.userLevel);
            msgModel.msgType = TCMsgModelType_NormalMsg;
            [self bulletMsg:msgModel];
            break;
        }
            
        case AVIMCMD_Custom_EnterLive: {
            LSMsgModel *msgModel = [[LSMsgModel alloc] init];
            msgModel.userId = info.imUserId;
            msgModel.userName = info.imUserName;
            msgModel.userMsg  =  @"进入房间";
            msgModel.userHeadImageUrl = info.imUserIconUrl;
            msgModel.userLevel = KString(info.userLevel);
            msgModel.msgType = TCMsgModelType_NormalMsg;
            _memberCount++;
            self.onlineNum.text = [NSString stringWithFormat:@"%d 人在线",_memberCount];
            [self EnterRoomAnimationWithUsername:info.imUserName Level:KString(info.userLevel)];
//            //收到新增观众消息，判断只有没在观众列表中，数量才需要增加1
//            if (![self isAlreadyInAudienceList:msgModel])
//            {
//                [_topView onUserEnterLiveRoom];
//            }
            [self bulletMsg:msgModel];
            
            break;
        }
            
        case AVIMCMD_Custom_ExitLive: {
            LSMsgModel *msgModel = [[LSMsgModel alloc] init];
            msgModel.userId = info.imUserId;
            msgModel.userName = info.imUserName;
            msgModel.userMsg  =  @"退出房间";
            msgModel.userHeadImageUrl = info.imUserIconUrl;
            msgModel.userLevel = KString(info.userLevel);
            msgModel.msgType = TCMsgModelType_NormalMsg;
            _memberCount--;
            self.onlineNum.text = [NSString stringWithFormat:@"%d 人在线",_memberCount];
            [self bulletMsg:msgModel];
            
            break;
        }
            
        case AVIMCMD_Custom_Like: {
            LSMsgModel *msgModel = [[LSMsgModel alloc] init];
            msgModel.userId = info.imUserId;
            msgModel.userName = info.imUserName;
            msgModel.userMsg  =  @"点了个赞";
            msgModel.userLevel = KString(info.userLevel);
            msgModel.userHeadImageUrl = info.imUserIconUrl;
            msgModel.msgType = TCMsgModelType_Praise;
            
            [self bulletMsg:msgModel];
//            [self showLikeHeart];
            break;
        }
            
        case AVIMCMD_Custom_Danmaku: {
            LSMsgModel *msgModel = [[LSMsgModel alloc] init];
            msgModel.userId = info.imUserId;
            msgModel.userName = info.imUserName;
            msgModel.userMsg  =  msgText;
            msgModel.userLevel = KString(info.userLevel);
            msgModel.userHeadImageUrl = info.imUserIconUrl;
            msgModel.msgType = TCMsgModelType_NormalMsg;
            
            [self bulletMsg:msgModel];
            break;
        }
        case AVIMCMD_Star_Present: {
            LSMsgModel *msgModel = [[LSMsgModel alloc] init];
            msgModel.userId = info.imUserId;
            msgModel.userName = info.imUserName;
            msgModel.userMsg  =  msgText;
            msgModel.userLevel = KString(info.userLevel);
            msgModel.userHeadImageUrl = info.imUserIconUrl;
            msgModel.msgType = TCMsgModelType_NormalMsg;
            
            [self bulletMsg:msgModel];
            break;
        }
        case AVIMCMD_Custom_RedPaper: {
            LSMsgModel *msgModel = [[LSMsgModel alloc] init];
            msgModel.userId = info.imUserId;
            msgModel.userName = info.imUserName;
            msgModel.userMsg  =  msgText;
            msgModel.userLevel = KString(info.userLevel);
            msgModel.userHeadImageUrl = info.imUserIconUrl;
            msgModel.msgType = TCMsgModelType_NormalMsg;
            
            [self bulletMsg:msgModel];
            break;
        }
        case AVIMCMD_Fans_Present: {
            LSMsgModel *msgModel = [[LSMsgModel alloc] init];
            msgModel.userId = info.imUserId;
            msgModel.userName = info.imUserName;
            //分割字符串 取出礼物位置
            NSArray *array = [msgText componentsSeparatedByString:@","];
            NSString *position = array[1];
            msgModel.userMsg  =  array[0];
            msgModel.userHeadImageUrl = info.imUserIconUrl;
            msgModel.userLevel = KString(info.userLevel);
            msgModel.msgType = TCMsgModelType_NormalMsg;
            self.sendUserName.text = msgModel.userName;
            self.presentNumImg.image = [UIImage imageNamed:_presentArr[[position intValue]]];
            [self.delegate giftAnimationWithMsgModel:msgModel];
            [self bulletMsg:msgModel];
            break;
        }
        case AVIMCMD_Star_ExitLive: {
            LSMsgModel *msgModel = [[LSMsgModel alloc] init];
            msgModel.userId = info.imUserId;
            msgModel.userName = info.imUserName;
            msgModel.userMsg  =  msgText;
            msgModel.userLevel = KString(info.userLevel);
            msgModel.userHeadImageUrl = info.imUserIconUrl;
            msgModel.msgType = TCMsgModelType_NormalMsg;
            [self bulletMsg:msgModel];
            [self.delegate starLiveroom];
            break;
        }
            
        default:
            break;
    }
}

- (void)onRecvGroupSystemMessage:(TIMGroupSystemElem *)msg {
    // 群被解散
    if (msg.type == TIM_GROUP_SYSTEM_DELETE_GROUP_TYPE) {
    }
}

- (void)msgInputView {
    if (!_msgInputView) {
        //输入框
        _msgInputView = [[UIView alloc] initWithFrame:CGRectMake(0, self.height, self.width, MSG_TEXT_SEND_VIEW_HEIGHT )];
        _msgInputView.backgroundColor = [UIColor whiteColor];
        
        UIButton *sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        sendBtn.frame = CGRectMake(self.width - 15 - MSG_TEXT_SEND_BTN_WIDTH, 0, MSG_TEXT_SEND_BTN_WIDTH, MSG_TEXT_SEND_VIEW_HEIGHT);
        [sendBtn setTitle:@"发送" forState:UIControlStateNormal];
        [sendBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
        [sendBtn setTitleColor:UIColorFromRGB(0x0ACCAC) forState:UIControlStateNormal];
        [sendBtn setBackgroundColor:[UIColor clearColor]];
        [sendBtn addTarget:self action:@selector(clickSend:) forControlEvents:UIControlEventTouchUpInside];
        
        _msgInputFeild = [[UITextField alloc] initWithFrame:CGRectMake(10,7.5,sendBtn.left - 20,MSG_TEXT_SEND_FEILD_HEIGHT)];
        _msgInputFeild.backgroundColor = [UIColor clearColor];
        _msgInputFeild.returnKeyType = UIReturnKeySend;
        _msgInputFeild.borderStyle = UITextBorderStyleRoundedRect;
        _msgInputFeild.placeholder = @"和大家说点什么吧";
        _msgInputFeild.delegate = self;
        _msgInputFeild.textColor = [UIColor blackColor];
        _msgInputFeild.font = [UIFont systemFontOfSize:14];
        
        [_msgInputView addSubview:_msgInputFeild];
        [_msgInputView addSubview:sendBtn];
        [self addSubview:_msgInputView];

    }

    
    [_msgInputFeild becomeFirstResponder];
}

#pragma mark -- 发送消息
- (void)clickSend:(UIButton *)sender {
    [self textFieldShouldReturn:_msgInputFeild];
}

//监听键盘高度变化
-(void)keyboardFrameDidChange:(NSNotification*)notice
{
    NSDictionary * userInfo = notice.userInfo;
    NSValue * endFrameValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect endFrame = endFrameValue.CGRectValue;

    if (self.is_Msg == YES) {
        _msgInputView.hidden = NO;
    } else {
        _msgInputView.hidden = YES;
    }
    [UIView animateWithDuration:0.25 animations:^{
        if (endFrame.origin.y == self.height) {
            _msgInputView.y =  endFrame.origin.y;
        }else{
            _msgInputView.y =  endFrame.origin.y - _msgInputView.height;
        }
    }];
}


#pragma mark -- 发消息
- (IBAction)SendMessage:(id)sender {
    [self.delegate functionClickWithSign:@"1" FunctionView:self];
}
#pragma mark -- 送礼物
- (IBAction)SendPresent:(id)sender {
    [self.delegate functionClickWithSign:@"2" FunctionView:self];
}

#pragma mark -- 发红包
- (IBAction)SendRedPaper:(id)sender {
    [self.delegate functionClickWithSign:@"3" FunctionView:self];
}
#pragma mark -- 摄像头
- (IBAction)SwitchCamera:(id)sender {
    [self.delegate functionClickWithSign:@"4" FunctionView:self];
}

#pragma mark -- 美颜
- (IBAction)Face:(id)sender {
    [self.delegate functionClickWithSign:@"5" FunctionView:self];
}

#pragma mark -- 关闭直播
- (IBAction)closeLiving:(id)sender {
    [self.delegate functionClickWithSign:@"6" FunctionView:self];
}


-(void)bulletMsg:(LSMsgModel *)msgModel{
    [self.msgTableView bulletNewMsg:msgModel];
    
    if (msgModel.msgType == TCMsgModelType_MemberEnterRoom || msgModel.msgType == TCMsgModelType_MemberQuitRoom) {
    }
}


#pragma mark UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if (textField == _msgInputFeild) {
        self.is_Msg = YES;
    } else {
        self.is_Msg = NO;
    }
    _msgInputFeild.text = @"";
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    _msgInputFeild.text = textField.text;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    NSString *textMsg = [textField.text stringByTrimmingCharactersInSet:[NSMutableCharacterSet whitespaceCharacterSet]];
    if (textMsg.length <= 0) {
        textField.text = @"";
//        [HUDHelper alert:@"消息不能为空"];
        return YES;
    }
    UserModel *model = [[LSUserInfoManager sharedManager] currentUserInfo];
    LSMsgModel *msgModel = [[LSMsgModel alloc] init];
    msgModel.userName = model.u_nickname;
    msgModel.userMsg  = textMsg;
    msgModel.userHeadImageUrl = [[LSUserInfoManager sharedManager] currentUserInfo].u_avatar;
    msgModel.msgType = TCMsgModelType_NormalMsg;
    msgModel.userLevel = KString(model.level);
    [_msgHandler sendTextMessage:User_ID nickName:model.u_nickname headPic:model.u_avatar msg:textMsg Level:model.level];
    [self bulletMsg:msgModel];
    [_msgInputFeild resignFirstResponder];
    return YES;
}


#pragma mark -- touch 事件
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    if ([self.delegate respondsToSelector:@selector(CloseFansPresentView)]) {
        [self.delegate CloseFansPresentView];
    }
}


@end
